﻿using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Dialogs;
using SharpSoft.WPF;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FilesManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public System.Collections.ObjectModel.ObservableCollection<System.IO.FileInfo> Files
        {
            get { return (System.Collections.ObjectModel.ObservableCollection<System.IO.FileInfo>)GetValue(FilesProperty); }
            set { SetValue(FilesProperty, value); }
        }

        public static readonly DependencyProperty FilesProperty =
            DependencyProperty.Register("Files", typeof(System.Collections.ObjectModel.ObservableCollection<System.IO.FileInfo>), typeof(MainWindow), new PropertyMetadata(default(System.Collections.ObjectModel.ObservableCollection<System.IO.FileInfo>)));



        private void btn_openFolder_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new CommonOpenFileDialog();
            dialog.IsFolderPicker = true;
            CommonFileDialogResult result = dialog.ShowDialog();
            if (result == CommonFileDialogResult.Ok)
            {
                var fileName = dialog.FileName;
                // Console.WriteLine("文件夹名字：" + fileName);
                txt_folder.Text = fileName;
                reloadFolder(fileName);
            }
        }

        private void reloadFolder(string folder)
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folder);
            System.IO.FileInfo[] files;
            if (!string.IsNullOrWhiteSpace(txt_pat.Text))
            {
                files = di.GetFiles(txt_pat.Text);
            }
            else
            {
                files = di.GetFiles();
            }

            this.Files = new System.Collections.ObjectModel.ObservableCollection<System.IO.FileInfo>(files);
        }

        private void btn_sort_Click(object sender, RoutedEventArgs e)
        {
            if (Files != null)
            {
                if (string.IsNullOrEmpty(txt_reg.Text))
                {
                    Files.OrderBy(fi => fi.Name);
                }
                else
                {
                    var b = cb_num.IsChecked.GetValueOrDefault();
                    var files = Files.ToArray();
                    Regex regex = new Regex(txt_reg.Text, RegexOptions.None);

                    Array.Sort(files, (f1, f2) =>
                    {
                        var match1 = regex.Match(f1.Name);
                        var match2 = regex.Match(f2.Name);
                        if (match1.Success && match2.Success)
                        {
                            if (b)
                            {
                                return Comparer.Default.Compare(int.Parse(match1.Value), int.Parse(match2.Value));
                            }
                            else
                            {
                                return Comparer.Default.Compare(match1.Value, match2.Value);
                            }
                        }
                        else
                        {
                            return Comparer.Default.Compare(f1.Name, f2.Name);
                        }
                    });
                    this.Files = new System.Collections.ObjectModel.ObservableCollection<System.IO.FileInfo>(files);

                }

            }
        }

        private void cb_num_Checked(object sender, RoutedEventArgs e)
        {
            txt_reg.Text = "(\\d+)";
        }

        private void btn_rename_Click(object sender, RoutedEventArgs e)
        {
            if (Files != null)
            {
                if (string.IsNullOrWhiteSpace(txt_temp.Text))
                {
                    MessageBox.Show("文件名模板为空。");
                    return;
                }
                try
                {
                    string.Format(txt_temp.Text, 1, ".jpg");
                }
                catch (Exception)
                {
                    MessageBox.Show("文件名模板错误。");
                    return;
                }
                int i = 0;
                foreach (var item in this.Files)
                {
                    i++;
                    var ext = System.IO.Path.GetExtension(item.Name);
                    var fullname = System.IO.Path.Combine(item.Directory.FullName, string.Format(txt_temp.Text, i, ext));
                    System.IO.File.Move(item.FullName, fullname);
                }
                reloadFolder(txt_folder.Text);
            }
        }

        private void btn_filter_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txt_folder.Text))
            {
                reloadFolder(txt_folder.Text);
            }
        }

        private async void btn_moveToRoot_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new CommonOpenFileDialog();
            dialog.IsFolderPicker = true;
            CommonFileDialogResult result = dialog.ShowDialog();
            if (result == CommonFileDialogResult.Ok)
            {
                var fileName = dialog.FileName;
                var wait = await this.WaitAsync("正在处理...");
                try
                {
                    await MoveToRootAsync(wait, fileName, fileName);
                    await this.SampleAsync("处理完成。", ThemeColor.Success);
                }
                catch (Exception ex)
                {
                    await this.SampleAsync("处理失败。" + ex.Message, ThemeColor.Error);
                }
                finally
                {
                    wait.Close();
                }

            }
        }

        private async Task MoveToRootAsync(WaittingDialog dlg, string root, string currentFolder)
        {
            var files = System.IO.Directory.GetFiles(currentFolder);
            foreach (var file in files)
            {
                dlg.Content = file;
                await Task.Run(() =>
                {
                    System.IO.File.Move(file, System.IO.Path.Combine(root, System.IO.Path.GetFileName(file)), false);
                });
            }
            var subs = System.IO.Directory.GetDirectories(currentFolder);
            foreach (var item in subs)
            {
                await MoveToRootAsync(dlg, root, item);
            }
        }
    }
}
